// SecurityProjectDlg.cpp : implementation file
//



#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#pragma once
// CSecurityProjectDlg dialog
#include "stdafx.h"
#include "SecurityProject.h"
#include "SecurityProjectDlg.h"
#include "CreateUser.h"
#include "AccountManagementDlg.h"


CSecurityProjectDlg::CSecurityProjectDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSecurityProjectDlg::IDD, pParent)
	, m_servAdd(_T(""))
	, m_chatString(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CSecurityProjectDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDITSERVER, m_servAdd);
	DDX_Text(pDX, IDC_EDITMSG, m_msgString);
	DDX_Text(pDX, IDC_EDITCHAT, m_chatString);
	DDX_Control(pDX, IDC_LIST1, m_listname);
	DDX_Control(pDX, IDC_EDITMSG, m_msg);
	DDX_Control(pDX, IDC_LIST_ONLINE, m_lstOnline);
}

BEGIN_MESSAGE_MAP(CSecurityProjectDlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTONCREATEACCOUNT, &CSecurityProjectDlg::OnBnClickedButtoncreateaccount)
	ON_BN_CLICKED(IDC_BUTTONLOGIN, &CSecurityProjectDlg::OnBnClickedButtonlogin)
	ON_BN_CLICKED(IDC_BUTTONLOGOUT, &CSecurityProjectDlg::OnBnClickedButtonlogout)
	ON_BN_CLICKED(IDC_BUTTONCLOSE, &CSecurityProjectDlg::OnBnClickedButtonclose)
	ON_BN_CLICKED(IDC_BUTTONCREATEACCOUNT_VIP, &CSecurityProjectDlg::OnBnClickedButtoncreateaccountVip)
	ON_BN_CLICKED(IDC_BUTTONDELETEACCOUNT, &CSecurityProjectDlg::OnBnClickedButtondeleteaccount)
	ON_BN_CLICKED(IDC_BUTTONUPDATEACCOUNT, &CSecurityProjectDlg::OnBnClickedButtonupdateaccount)
	ON_BN_CLICKED(IDC_BUTTONSEND, &CSecurityProjectDlg::OnBnClickedButtonsend)
	ON_MESSAGE (WM_SOCKET, SockMsg)
	ON_WM_CLOSE()
	//ON_BN_CLICKED(IDC_BUTTONPROFILE, &CSecurityProjectDlg::OnBnClickedButtonprofile)
//	ON_BN_CLICKED(IDC_BUTTONMANAGEACCOUNT, &CSecurityProjectDlg::OnBnClickedButtonmanageaccount)
ON_BN_CLICKED(IDC_BUTTON_MANAGE, &CSecurityProjectDlg::OnBnClickedButtonManage)
ON_BN_CLICKED(IDC_BUTTON1, &CSecurityProjectDlg::OnBnClickedButton1)
END_MESSAGE_MAP()


// CSecurityProjectDlg message handlers

BOOL CSecurityProjectDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	InitListControl();
	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	WORD wVersionRequested;
	WSADATA wsaData;
	wVersionRequested=MAKEWORD(2,2);
	int err=WSAStartup(wVersionRequested,&wsaData);
	if (err!=0)
		MessageBox(_T("Can't initialize socket"));

	m_servAdd = _T("127.0.0.1");
	isServerShutdown = true;
	UpdateData(FALSE);

	// TODO: Add extra initialization here
	if (ConnectToServer())
	{
		MessageBox(_T("Connect failed"), _T("Error"), MB_OK);
		::PostQuitMessage(1);
	}
	else
	{
		MessageBox(_T("Connect succeeded"), _T("Info"), MB_OK);
	}
	m_AccDlg = NULL;
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CSecurityProjectDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CSecurityProjectDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CSecurityProjectDlg::OnBnClickedButtoncreateaccount()
{
	// TODO: Add your control notification handler code here
	CCreateUser* crUdlg = new CCreateUser(this);
	crUdlg->DoModal();
	
	

}

void CSecurityProjectDlg::OnBnClickedButtonlogin()
{
	// TODO: Add your control notification handler code here
	CString username;
	CString password;
	CString message = _T("");
	GetDlgItemText(IDC_EDIT_LOG_NAME,username);
	GetDlgItemText(IDC_EDIT_LOG_PASS,password);
    
	if(username != _T("") && password != _T(""))
	{
		//Message de create account co cau truc :  AXusernameYpasswordZDescription 
		// X,Y,Z la kick thuoc username,pass,description (co dinh thieu dai X,Y,Z la 2 )
		CString message = _T("A3");
		if(username.GetLength() < 10)
			message += _T("0");
		message += ToCString(username.GetLength()) + username;
		if(password.GetLength() < 10)
			message += _T("0");
		message += ToCString(password.GetLength()) + password;
		m_nameString = username;
		SendMessageToServer(message);

	}


}

void CSecurityProjectDlg::OnBnClickedButtonlogout()
{
	// TODO: Add your control notification handler code here
	SendMessageToServer(_T("6"));
	GetDlgItem(IDC_BUTTONLOGIN)->EnableWindow(TRUE);
	GetDlgItem(IDC_BUTTONLOGOUT)->EnableWindow(FALSE);
	GetDlgItem(IDC_BUTTON_MANAGE)->EnableWindow(FALSE);
	m_lstOnline.DeleteAllItems();

}

void CSecurityProjectDlg::OnBnClickedButtonclose()
{
	// TODO: Add your control notification handler code here
	::PostQuitMessage(0);
}

void CSecurityProjectDlg::OnBnClickedButtoncreateaccountVip()
{
	// TODO: Add your control notification handler code here
}

void CSecurityProjectDlg::OnBnClickedButtondeleteaccount()
{
	// TODO: Add your control notification handler code here
}

void CSecurityProjectDlg::OnBnClickedButtonupdateaccount()
{
	// TODO: Add your control notification handler code here
}

void CSecurityProjectDlg::OnBnClickedButtonsend()
{
	// TODO: Add your control notification handler code here
		// TODO: Add your control notification handler code here
	UpdateData();
	CString strchat = m_chatString;
	CString message;
	if(strchat[0] == '/')//Chat rieng
	{
		strchat.Delete(0,1);
		int index = strchat.Find(' ',0);
		if(index != -1)
		{
			CString username = strchat.Mid(0,index);
			strchat.Delete(0,index+1);
			message = _T("31");
			if(username.GetLength() < 10)
				message += _T("0");
			message += ToCString(username.GetLength()) + username+strchat;
			SendMessageToServer(message);
			m_msgString += m_nameString + _T(" : ") + username + _T(" : ") + strchat + _T("\r\n");  
			m_chatString="";
		}		
	}
	else//chat all
	{
		message = _T("30") + strchat;
		SendMessageToServer(message);
		m_msgString += m_nameString +  _T("[ALL]: ") + strchat + _T("\r\n");
		m_chatString="";
	}
	
	UpdateData(FALSE);
	m_msg.SetSel(m_msg.GetWindowTextLengthW(),m_msg.GetWindowTextLengthW());
}

// This function is used to connect to server
int CSecurityProjectDlg::ConnectToServer(void)
{
	// TODO: Add your control notification handler code here
	UpdateData();
	sClient = socket(AF_INET, SOCK_STREAM, 0);
    hostent* host=NULL;
	if (sClient == INVALID_SOCKET)
    {
        MessageBox(_T("socket() failed"));
    }
	char *pAnsiString = new char[100];
	wcstombs(pAnsiString, m_servAdd, 100);
    servAdd.sin_family = AF_INET;
    servAdd.sin_port = htons(PORT); 
	servAdd.sin_addr.s_addr = inet_addr( pAnsiString);	
	//Neu dia chi IP khong phai dang so nhu "172.29.20.20" ma dang ten
	// Vi du nhu "www.yahoo.com" phai goi ham gethostbyname() de phan dai thanh IP
	if (servAdd.sin_addr.s_addr==INADDR_NONE){
		host = gethostbyname(pAnsiString);
        if (host == NULL)
        {
            MessageBox(_T("Unable to resolve server"));
        }
        CopyMemory(&servAdd.sin_addr, host->h_addr_list[0],
            host->h_length);
	}
	int err=connect(sClient,(struct sockaddr*)&servAdd,sizeof(servAdd));
	if (err==SOCKET_ERROR){
		err = WSAGetLastError();
		MessageBox(_T("Connect Failed"));
		return 1;
	}
	
	WSAAsyncSelect(sClient,m_hWnd,WM_SOCKET,FD_READ|FD_CLOSE);
	msgType = 0;
	//
	UpdateData();

	UpdateData(false);
	return 0;
}

void CSecurityProjectDlg::OnClose()
{
	// TODO: Add your message handler code here and/or call default
	if (sClient!=INVALID_SOCKET)
		shutdown(sClient,SD_BOTH);
	closesocket(sClient);
	WSACleanup();
	CDialog::OnClose();
}

BOOL CSecurityProjectDlg::PreTranslateMessage(MSG *pMsg)
{
	if ( pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN )
	{
		int idCtrl= this->GetFocus()->GetDlgCtrlID();
		if ( idCtrl == IDC_EDITCHAT )
		{
			OnBnClickedButtonsend();
			return true;
		}
	}
	return CDialog::PreTranslateMessage(pMsg);
}

LRESULT CSecurityProjectDlg::SockMsg(WPARAM wParam, LPARAM lParam)
{
	if (WSAGETSELECTERROR(lParam))
    {
		 // Display the error and close the socket
         closesocket(wParam);
    }
	switch(WSAGETSELECTEVENT(lParam))
    {
		case FD_READ:
			//Ben server gui thong diep
			//Server se gui 2 loai thong diep: Gui kich thuoc (so int) va mang chua thong diep
			//Neu:
				//msgType=0: nhan so luong byte
				//msgType=1: nhan doan du lieu Chat
			if (!msgType){
				recv(sClient,(char*)&buffLength,sizeof(int),0);
				msgType=1;
			}
			else{
				char* buffer=new char[buffLength+1];
				char type;
				CString group;
				CString msg;
				recv(sClient,buffer,buffLength,0);
				buffer[buffLength]='\0';				
				msgType=0;
				type = buffer[0];
				msg= buffer+1;
				switch (type)
				{
				   case '0'://Thong diep thong bao cau server dan den close socket 
						m_msgString += "Thong bao: ";
						m_msgString += msg;
						m_msgString +="\r\n";
						UpdateData(false);
						isServerShutdown = false;
						shutdown(sClient,SD_BOTH);
						break;
					case '3'://Chat
						m_msgString += msg;
						m_msgString += "\r\n";
						UpdateData(false);
						m_msg.SetSel(m_msg.GetWindowTextLengthW(),m_msg.GetWindowTextLengthW());
						break;
					case '2'://Thong diep warning cua server
						m_msgString += "Thong bao: ";
						m_msgString += msg;
						m_msgString +="\r\n";
						UpdateData(false);
						break;
					case '4'://Thong bao 1 tai khoan vua dang nhap vao he thong
						group = msg.Mid(0,1);
						msg.Delete(0,1);
						if(group == _T("1"))
							group = _T("Vip");
						else
							group = _T("Normal");
						AddAccountToListOnline(msg,group);
						m_listname.AddString(msg);
						break;
					case '5'://Thong bao 1 tai khoan vua log out khoi he thong
						DelAccountInListOnline(msg);
						for(int k = 0;k < m_listname.GetCount();k++)
						{
							CString nameItem;
							m_listname.GetText(k,nameItem);
							if(nameItem == msg)
							{								
								m_listname.DeleteString(k);
								break;
							}
						}
						break;
					case 'A':
						ManageAccount(msg);
						break;
				}
				delete buffer;
			}
			break;
		case FD_CLOSE:
			if(isServerShutdown)
				m_msgString += "Thong bao: Server tat.\r\n";
			isServerShutdown = true;
			closesocket(wParam);
			GetDlgItem(IDC_BUTTONLOGIN)->EnableWindow(TRUE);
			GetDlgItem(IDC_BUTTONSEND)->EnableWindow(FALSE);
			GetDlgItem(IDC_EDITCHAT)->EnableWindow(FALSE);
			GetDlgItem(IDC_BUTTONLOGOUT)->EnableWindow(FALSE);
			UpdateData(false);
			break;
	}
	return 0;
}

void CSecurityProjectDlg::SendMessageToServer(CString msg)
{
	int Len = msg.GetLength();
	char *sendBuff = new char[Len+1];
	wcstombs(sendBuff, msg, Len+1);
	//Send kich thuoc truoc
	send(sClient,(char*)&Len,sizeof(Len),0);
	send(sClient,(char*)sendBuff,Len,0);

}

CString CSecurityProjectDlg::ToCString(int iNum)
{
	char buffer[100];
	char* str = itoa(iNum, buffer, 10);
	return CString(str);
}
//Xu ly cac message co prefix la 'A'
void CSecurityProjectDlg::ManageAccount(CString msg)
{		
	CString username,description;
	CAccountManagementDlg* dlg = (CAccountManagementDlg*) m_AccDlg;
	int len;
	char Type = msg[0];
	msg.Delete(0,1);
	switch(Type)
	{
	case '1'://Tao tai khoan thanh cong	
		MessageBox(msg);
		if(m_AccDlg)
		{
			CAccountManagementDlg* dlg = (CAccountManagementDlg*) m_AccDlg;
			dlg->LoadAccountList();
		}
		break;
	case '2': //Tao tai khoan that bai
		MessageBox(msg);
		break;
	case '4':
		m_groupType = msg;		
		GetDlgItem(IDC_BUTTONLOGIN)->EnableWindow(FALSE);
		GetDlgItem(IDC_BUTTONLOGOUT)->EnableWindow(TRUE);
		GetDlgItem(IDC_BUTTONSEND)->EnableWindow(TRUE);
		UpdateGroupControl(m_groupType);		
		break;
	case '5':
		MessageBox(msg);		
		break;
	case '8':		
		len = _ttoi(msg.Mid(0,2));
		msg.Delete(0,2);
		username = msg.Mid(0,len);
		msg.Delete(0,len);

		//Lay description
		len = _ttoi(msg.Mid(0,2));
		msg.Delete(0,2);
		description = msg.Mid(0,len);
		msg.Delete(0,len);		
		dlg->AddAccountToList(username,description);		
		
		break;
	case 'A'://Thong bao edit thanh cong
		MessageBox(msg);
		dlg->LoadAccountList();
		break;
	case 'B'://Thong bao edit that bai
		MessageBox(msg);
		break;
	case 'D'://Thong bao delete thanh cong
		MessageBox(msg);
		dlg->LoadAccountList();
		break;
	case 'E'://Thong bao delete that bai
		MessageBox(msg);
		break;

	}
}

void CSecurityProjectDlg::UpdateGroupControl(CString groupType)
{
	if(groupType == _T("1"))//User Vip
	{
		GetDlgItem(IDC_BUTTON_MANAGE)->EnableWindow(TRUE);
	}
	else
	{
		GetDlgItem(IDC_BUTTON_MANAGE)->EnableWindow(FALSE);
	}
}
void CSecurityProjectDlg::OnBnClickedButtonprofile()
{
	// TODO: Add your control notification handler code here

}

//void CSecurityProjectDlg::OnBnClickedButtonmanageaccount()
//{
//	// TODO: Add your control notification handler code here
//	
//	m_AccDlg = new CAccountManageDlg(this);
//	m_AccDlg->DoModal();	
//
//}

void CSecurityProjectDlg::OnBnClickedButtonManage()
{
	// TODO: Add your control notification handler code here
	m_AccDlg = new CAccountManagementDlg(this);	
	m_AccDlg->DoModal();
	
}

void CSecurityProjectDlg::OnBnClickedButton1()
{
	// TODO: Add your control notification handler code here
}

void CSecurityProjectDlg::InitListControl()
{
	ListView_SetExtendedListViewStyle(m_lstOnline, LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT);	
	m_lstOnline.InsertColumn(0, _T("Username"), LVCFMT_LEFT, 110);
	m_lstOnline.InsertColumn(1, _T("Group"), LVCFMT_LEFT, 50);
	
}

void CSecurityProjectDlg::AddAccountToListOnline(CString username, CString group)
{
	m_lstOnline.InsertItem(0, NULL);
	m_lstOnline.SetItemText(0, 0, username);
	m_lstOnline.SetItemText(0, 1, group);
	UpdateData(FALSE);

}

void CSecurityProjectDlg::DelAccountInListOnline(CString username)
{
	int count = m_lstOnline.GetItemCount();
	CString name;
	for(int i = 0 ; i < count ; i ++)
	{
		name = m_lstOnline.GetItemText(i,0);
		if(name == username)
		{
			m_lstOnline.DeleteItem(i);
			break;
		}
	}
}